package com.shengdan.pocket_file.pocketfile;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.os.Build;
import android.os.ParcelUuid;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * author: ChenShengDan .
 * date:   2022/12/18
 * sence:
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class BluetoothUtils {
    //厂商id
    private static final int MANUFACTURER_ID = 0x15;
    //广播uuid
    public static ParcelUuid BROADCAST_SERVICE_PARCEUUID = ParcelUuid.fromString("0000fff5-0000-1000-8000-000777f9b34fb");
    //    public static ParcelUuid BROADCAST_SERVICE_PARCEUUID = ParcelUuid.fromString("0000fff5-0000-1000-8000-000777f9b34fb");
    private static final String DeviceName = Build.MODEL;
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothLeAdvertiser mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
    BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    private static BluetoothUtils mInstance;

    public static synchronized BluetoothUtils getInstance() {
        if (mInstance == null) {
            mInstance = new BluetoothUtils();
        }
        return mInstance;
    }

    /**
     * 发送广播
     *
     * @param data
     * @param callback
     */
    @SuppressLint("MissingPermission")
    public void sendDataBroadcast(String data, AdvertiseCallback callback) {
        mBluetoothAdapter.setName(DeviceName);
        mBluetoothLeAdvertiser.startAdvertising(getAdvertiseSettings(), getBroadcastPacketData(),
                getBroadcastScanData(data.getBytes(StandardCharsets.UTF_8)), callback);
    }

    /**
     * 停止广播
     *
     * @param callback
     */
    @SuppressLint("MissingPermission")
    public void stopDataBroadcast(AdvertiseCallback callback) {
        mBluetoothLeAdvertiser.stopAdvertising(callback);
    }

    /**
     * 蓝牙扫描(接收数据)
     *
     * @param scanCallback
     */
    @SuppressLint("MissingPermission")
    public void receiveBroadcastData(ScanCallback scanCallback) {
        mBluetoothLeScanner.startScan(createScanFilter(), new ScanSettings.Builder().build(), scanCallback);
    }

    /**
     * 取消蓝牙扫描(接收数据)
     *
     * @param scanCallback
     */
    @SuppressLint("MissingPermission")
    public void unReceiveBroadcastData(ScanCallback scanCallback) {
        mBluetoothLeScanner.stopScan(scanCallback);
    }

    /**
     * 扫描过滤
     *
     * @return
     */
    private List<ScanFilter> createScanFilter() {
        List<ScanFilter> scanFilters = new ArrayList<>();
        scanFilters.add(new ScanFilter.Builder().setManufacturerData(MANUFACTURER_ID,null).build());
        return scanFilters;
    }

    /**
     * 广播设置
     *
     * @return
     */
    AdvertiseSettings getAdvertiseSettings() {
        return new AdvertiseSettings.Builder()
                //设置广播模式，以控制广播的功率和延迟。
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                //发射功率级别
                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                //不得超过180000毫秒。值为0将无时间限制广播。
                .setTimeout(0)
                //设置是否可以连接
                .setConnectable(false)
                .build();
    }

    /**
     * 初始化广播包
     *
     * @return AdvertiseData
     */
    public AdvertiseData getBroadcastPacketData() {
        return new AdvertiseData.Builder()
                //设置广播设备名称
                .setIncludeDeviceName(true)
                //设置发射功率级别
                .setIncludeDeviceName(true)
                .build();
    }

    /**
     * 初始化扫描响应包
     *
     * @param manufacturerData 厂商数据 byte[]
     * @return AdvertiseData
     */
    public AdvertiseData getBroadcastScanData(byte[] manufacturerData) {
        return new AdvertiseData.Builder()
                //隐藏广播设备名称
                .setIncludeDeviceName(false)
                //隐藏发射功率级别
                .setIncludeDeviceName(false)
                //设置广播的服务UUID,这里也会占有厂商自定义数据31字节
//                .addServiceUuid(BROADCAST_SERVICE_PARCEUUID)
                // .addServiceData()   也可用于添加数据
                //设置厂商数据 根据flag判断
                .addManufacturerData(MANUFACTURER_ID, manufacturerData)
                .build();
    }

    /**
     * 广播发送后的回调
     */
    public AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
        }
    };
}
